#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glut.h>
#include <stdio.h>

#include "cNoise.h"
#include "component.h"
#include "shaders.h"


cNoise::cNoise(Sync* sync) : Component(sync) {
}

cNoise::~cNoise() {
}
static void printProgramInfoLog(GLuint obj)
{
	GLint infologLength = 0, charsWritten = 0;
	glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength);
	if (infologLength > 2) {
		GLchar* infoLog = new GLchar [infologLength];
		glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog);
		printf("%s\n", infoLog);
		delete infoLog;
	}
}
void
cNoise::initialize() {
	glewInit();
	glProgram = glCreateProgram();
	fragmentShader = glCreateShader(GL_FRAGMENT_SHADER_ARB);

	glShaderSourceARB(fragmentShader, 1, &noise3D, NULL);
	glCompileShaderARB(fragmentShader);
	glAttachObjectARB(glProgram, fragmentShader);
	glLinkProgramARB(glProgram);

	paramTime = glGetUniformLocation(glProgram, "time");
	paramScale = glGetUniformLocation(glProgram, "scale");
	paramAlpha = glGetUniformLocation(glProgram, "alpha");

	printProgramInfoLog(glProgram);

	// Use The Program Object Instead Of Fixed Function OpenGL
	//glUseProgramObjectARB(my_program);
}

void
cNoise::draw(float time, float dt, float alpha) {
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glOrtho(-1, 1, -1, 1, 0, 100);
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
	//glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE);

	glClear(GL_DEPTH_BUFFER_BIT);

	glUseProgram(glProgram);
	glUniform1f(paramTime, time);
	glUniform1f(paramScale, 0.05f);
	glUniform1f(paramAlpha, sync->channel(SYNC_RANDOM));

	glBegin(GL_POLYGON);
	glVertex3f  (-1.5f, -1.5f, 0.0);
	glVertex3f  (-1.5f,  1.5f, 0.0);
	glVertex3f  ( 1.5f,  1.5f, 0.0);
	glVertex3f  ( 1.5f, -1.5f, 0.0);
	glEnd();

	glUseProgram(0);

	glDisable(GL_BLEND);

	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();
}
